/**
 * 
 */
package com.suixun.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.authority.controller.BaseManager;
import com.google.gson.Gson;
import com.suixun.entity.SimInfo;
import com.suixun.entity.form.SimInfoForm;
import com.suixun.entity.page.PageModel;
import com.suixun.service.SimInfoService;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/simInfoManage")
public class SimInfoManage extends BaseManager {
	@Resource
	private SimInfoService simInfoService;

	/**
	 * 查询所有的Sim卡列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "querySimInfo.json")
	@ResponseBody
	public Object querySimInfoList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SimInfoForm simInfoForm = new Gson().fromJson(param, SimInfoForm.class);
			return success(simInfoService.querySimInfolist(simInfoForm));
		} catch (Exception e) {
			logger("SimInfoManage querySimInfoList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 分页查询Sim卡列表
	 * 
	 * @return
	 */

	@RequestMapping(value = "querySimInfoList.json")
	@ResponseBody
	public Object querySimInfoListPage(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		
		try {
			SimInfoForm simInfoForm = null;
			if (StringUtil.isBlank(param)) {
				simInfoForm = new SimInfoForm();
			}else {
				simInfoForm = new Gson().fromJson(param, SimInfoForm.class);
			}
			return success(simInfoService.querySimInfolistPage(simInfoForm));
		} catch (Exception e) {
			logger("SimInfoManage querySimInfoListPage:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	
	/**
	 * 新增Sim卡
	 * 
	 * @return
	 */

	@RequestMapping(value = "addSimInfo.json")
	@ResponseBody
	public Object addSimInfo(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SimInfo simInfoinfo = new Gson().fromJson(param, SimInfo.class);
			if (simInfoinfo == null || StringUtil.isBlank(simInfoinfo.getIccid())) {
				return fail(Constant.EMPTY);
			}
			//先判断ICCID是否已存在
			SimInfoForm simInfoForm=new SimInfoForm();
			simInfoForm.setIccid(simInfoinfo.getIccid());
			SimInfo simInfo=simInfoService.querySimInfoByIccid(simInfoForm);
			if(simInfo!=null && simInfo.getId()!=null) {
				return fail(Constant.Sim.ICCID_IS_EXIST);
			}
			int res = simInfoService.addSimInfo(simInfoinfo, this.getUserId());
			
			if(res>0) {
				return success(res);
			}else {
				if (res == -1) {
					return fail("手机号已存在");
				}
				return fail(Constant.FAIL);
			}
		} catch (Exception e) {
			logger("SimInfoManage addSimInfo:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}

	/**
	 * 修改Sim卡
	 * 
	 * @return
	 */

	@RequestMapping(value = "modifySimInfo.json")
	@ResponseBody
	public Object modifySimInfo(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SimInfo simInfoinfo = new Gson().fromJson(param, SimInfo.class);
			if (simInfoinfo == null || StringUtil.isBlank(simInfoinfo.getIccid()) || simInfoinfo.getId()==null) {
				return fail(Constant.EMPTY);
			}
			//先判断Sim卡名称是否已存在
			SimInfoForm simInfoForm=new SimInfoForm();
			simInfoForm.setIccid(simInfoinfo.getIccid());
			SimInfo simInfo=simInfoService.querySimInfoByIccid(simInfoForm);
			if(simInfo!=null && simInfo.getId()!=null && simInfo.getId().intValue()!=simInfoinfo.getId().intValue())
				return fail(Constant.Sim.ICCID_IS_EXIST);
			int res = simInfoService.modifySimInfo(simInfoinfo, this.getUserId());
			
			if(res>0) {
				return success(res);
			}else {
				return fail(Constant.FAIL);
			}
		} catch (Exception e) {
			logger("SimInfoManage modifySimInfo:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 注销Sim卡
	 * 
	 * @return
	 */

	@RequestMapping(value = "deleteSimInfo.json")
	@ResponseBody
	public Object deleteSimInfo(String param) {
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			SimInfoForm simInfoForm = new Gson().fromJson(param, SimInfoForm.class);
			if (simInfoForm == null || StringUtil.isBlank(simInfoForm.getIds())) {
				return fail(Constant.EMPTY);
			}
			SimInfo simInfo=new SimInfo();
			simInfo.setIccid(simInfoForm.getIds());
			int res = simInfoService.delSimInfo(simInfoForm.getIds());
			
			if(res>0) {
				return success(res);
			}else {
				return fail(Constant.FAIL);
			}
		} catch (Exception e) {
			logger("SimInfoManage deleteSimInfo:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}

	}
	
	/**
	 * 导出excel，不做鉴权
	 * 
	 * @return
	 */

	@RequestMapping(value = "export_SimInfoList.json")
	@ResponseBody
	public Object exportSimInfoList(String param) {
		boolean bln = checkRight();
		if (!bln) {
			toRedirect(404);
		}
		if (param == null)
			param="";

		try {
			SimInfoForm simInfoForm = new Gson().fromJson(param, SimInfoForm.class);
			ArrayList<String> listParm = new ArrayList<String>();
			listParm.add(Constant.Excel.OPERATIONS);
			listParm.add(Constant.Excel.SIM);
			listParm.add(Constant.Excel.ICCID);
			listParm.add("激活姓名");
			listParm.add("身份证号");
			listParm.add("关联设备");
			listParm.add("绑定时间");
			
			List<List<String>> listValue=new LinkedList<List<String>>();
			//限制最多导出1万条数据，前端可以通过细化查询条件来多次导出
			if(StringUtil.isBlank(simInfoForm.getPagecount()))
				simInfoForm.setPagecount(Constant.Excel.EXPORT_ROWS);
			PageModel<SimInfo> page = simInfoService.querySimInfolistPage(simInfoForm);
			List<SimInfo> list=page.getQueryresult();

			for (int m = 0; m < list.size(); m++) {
				List<String> value=new LinkedList<String>();
				SimInfo simInfo = list.get(m);
				value.add(simInfo.getOperations());
				value.add(simInfo.getPhone());
				value.add(simInfo.getIccid());
				value.add(simInfo.getPeoplename());
				value.add(simInfo.getPeopleidcard());
				value.add(simInfo.getMdtid());
				value.add(DateUtil.formatDateToString(simInfo.getBindtime(), null));
				listValue.add(value);
				simInfo = null;
			}
			
			// 创建新的Excel 工作簿
			HSSFWorkbook workbook = exportDeviceList(Constant.Excel.SIM_EXCEL,listParm,listValue);
			HttpServletResponse response=this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=simInfolist.xls");
			workbook.write(this.getResponse().getOutputStream());

		} catch (Exception e) {
			logger("SimInfoManage exportSimInfoList:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();
	}
	
	
	/**
	 * 
	 * <p>Title: exportTamplate</p>
	 * <p> 功能描述:导入excel模板下载 </p>
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "export_simTamplate.json")
	@ResponseBody
	public Object exportTamplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook=null;
			List<List<String>> listValue = new LinkedList<List<String>>();
			listParm.add(Constant.Excel.OPERATIONS);
			listParm.add(Constant.Excel.SIM);
			listParm.add(Constant.Excel.ICCID);
			listExample.add(Constant.Sim.EXAMPLE_OPERATIONS);
			listExample.add(Constant.Sim.EXAMPLE_SIM);
			listExample.add(Constant.Sim.EXAMPLE_ICCID);
			listExample.add(Constant.Excel.WARNING);
			// 创建新的Excel 工作簿
			workbook = exportDeviceList(Constant.Excel.SIM_EXCEL, listParm,listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=importSimInitList.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("SimInfoManage exportTamplate:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();
	}
	/**
	 * 
	 * <p>Title: cancel</p>
	 * <p> 功能描述:撤销导入数据库操作 </p>
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "cancelSimImport.json")
	public Object cancel(){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			int isdeleted=simInfoService.cancelSimImport();
			if(isdeleted==-1){
				return fail(Constant.Sim.SIM_IS_BIND);
			}else if(isdeleted==-2||isdeleted==0){
				return fail(Constant.Sim.SIM_IS_EMPTY);
			}else{
				Map<String,Object> result = new HashMap<String,Object>();
				result.put("result", Constant.SUCCESS);
				return success(result);
			}
		}catch (Exception e) {
			logger("SimInfoManage cancel:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	/**
	 * 
	 * <p>Title: querySimTmpList</p>
	 * <p> 功能描述:查询最近一次入库 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "querySimTmpList.json")
	public Object querySimTmpList(String param){
		boolean bln = checkRight();
		if (!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if (param == null) {
			param="";
		}
		try {
			SimInfoForm simInfoForm = new Gson().fromJson(param, SimInfoForm.class);
			return success(simInfoService.querySimTmp(simInfoForm));
		} catch (Exception e) {
			logger("SimInfoManage querySimTmpList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 
	 * <p>Title: importSim</p>
	 * <p> 功能描述:将excel数据保存到数据库 </p>
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "importSim.json", method = RequestMethod.POST)
	public Object importSim(@RequestParam("file") MultipartFile file,HttpServletRequest request
			,HttpServletResponse response){
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		InputStream fileReport = null;
		try {
			fileReport=file.getInputStream();
			String fileName = file.getOriginalFilename();
			if (fileName.endsWith("xlsx")) {
				return fail(Constant.Excel.TYPE_IS_FALSE);
			}
			//把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			String isAdd=simInfoService.importSim(wb);
			if(Constant.Excel.IMPORT_TRUE.equals(isAdd)){
				return success();
			}else{
				if (Constant.Excel.EXCEL_IS_EXIST.equals(isAdd)) {
					//查询临时重复表
					return success(simInfoService.querySimRepeat());
				}else {
					return fail(isAdd);
				}
			}
		} catch (Exception e) {
			logger("SimInfoManage importSim:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}finally{
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("DeviceInitManage importDevice:"+e.getMessage(),e);
			}
		}
	}
}
